<template>
    <view class="template-ucharts tn-safe-area-inset-bottom">
        <!-- <view class="stats-section">
            <view class="stats-grid">
                <view class="stat-item">
                    <text class="stat-value">{{ averageSleepTime }}</text>
                    <text class="stat-label">平均睡眠时间</text>
                </view>
                <view class="stat-item">
                    <text class="stat-value">{{ weeklyProgress }}%</text>
                    <text class="stat-label">本周进度</text>
                </view>
                <view class="stat-item">
                    <text class="stat-value">{{ totalSleepDays }}天</text>
                    <text class="stat-label">总记录天数</text>
                </view>
            </view>
        </view> -->
        <view class="top-bar dl-flex center p-y-4">
            <main-switch :data="currentCategory" :options="options" @change="handleCategory"></main-switch>
        </view>

        <view>
            <view class="tn-padding-top-xl tn-padding-bottom-xl">
                <view class="tn-flex tn-flex-row-between tn-flex-col-center">
                    <view class="justify-content-item tn-margin tn-text-bold tn-text-lg">
                        {{ type == 'weight' ? '体重趋势' : '睡眠趋势' }}
                    </view>
                    <view class="justify-content-item tn-margin-right tn-padding-xs tn-text-sm tn-bg-gray--light tn-radius tn-color-gray--dark"></view>
                </view>
                <view class="" style="min-height: 500rpx">
                    <qiun-data-charts canvas2d type="line" :opts="monthOpts" :chartData="monthChartData" />
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import { formatDate } from '@/store/utils';
const record = uniCloud.importObject('record', {
    customUI: true
});
export default {
    data() {
        return {
            // 生成近7天的日期数组
            type: '',
            currentCategory: '7',
            averageSleepTime: '7.5h',
            weeklyProgress: 85,
            totalSleepDays: 0,
            options: [
                {
                    text: '近 7 天',
                    value: '7'
                },
                {
                    text: '近 30 天',
                    value: '30'
                }
            ],
            // 收入支出
            monthChartData: {},
            monthOpts: {
                color: ['#4B98FE', '#00D05E', '#FFAC00', '#FB6A67', '#957BFE', '#00B9FE', '#FE871B', '#00C8B0', '#F674D6'],
                padding: [15, 15, 0, 15],
                dataLabel: false,
                xAxis: {
                    labelCount:15,
                    fontSize:10,
                    marginTop:10,
                    rotateAngle:30,
                    rotateLabel: true,
                    disableGrid: true
                },
                yAxis: {
                    gridType: 'dash',
                    dashLength: 2
                },
                extra: {
                    line: {
                        type: 'straight',
                        width: 2,
                        activeType: 'hollow'
                    }
                }
            }
        };
    },
    onShow() {},
    onLoad(options) {
        const user=uni.getStorageSync('user');
        if (user) {
            this.type = options.type;
            this.month=options.month;
            this.year=options.year;
            this.load(this.type,this.month,this.year);
        } else {
            uni.showToast({
                title: '请先登录',
                icon: 'none'
            });
            setTimeout(() => {
                uni.redirectTo({
                    url: '/pages/login/login'
                });
            }, 1000);
        }
    },
    methods: {
        generateLastDays(n) {
            const dates = [];
            for (let i = n - 1; i >= 0; i--) {
                const date = new Date();
                date.setDate(date.getDate() - i);
                dates.push(formatDate(date, 'yyyy-MM-dd'));
            }
            return dates;
        },
        handleCategory(data) {
            this.currentCategory = data.value;
            this.load(this.type,this.month,this.year);
        },
        // 收入支出 绘制
        load(type,month,year) {
            uni.showLoading({
                title: '加载中...',
                mask: true
            });
            const user=uni.getStorageSync('user');
            record
                .queryRecordByDay({
                    user_id: user._id,
                    category: type,
                    days: Number(this.currentCategory)
                })
                .then((res) => {
                    uni.hideLoading();
                    this.totalSleepDays = res.data.length;
                    var data = {};
                    res.data.forEach((item) => {
                        data[item.full_date] = item.data;
                    });
                    var categories = this.generateLastDays(this.currentCategory);
                    let config = {
                        categories: categories.map((item) => formatDate(new Date(item), 'MM-dd')),
                        series: [
                            {
                                name: type == 'weight' ? '体重' : type == 'sleep' ? '睡眠' : '热量',
                                data: categories.map((item) => data[item] || null),
                                legendShape: 'circle',
                                color: '#4B98FE'
                            }
                        ]
                    };
                    this.monthChartData = JSON.parse(JSON.stringify(config));
                });
        }
    }
};
</script>
<style lang="scss" scoped>
/* 间隔线 start*/
.tn-strip-bottom {
    width: 100%;
    border-bottom: 20rpx solid #f8f7f8;
}

/* 间隔线小 start*/
.tn-strip-bottom-min {
    width: 100%;
    border-bottom: 1rpx solid #f8f7f8;
}

.stats-section {
    border-radius: 24rpx;
    .section-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 24rpx;
    }
}
.stats-section {
    margin: 16rpx 32rpx;
    background-color: #fff;
    border-radius: 24rpx;
    padding: 40rpx;
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.08);
}

.stats-grid {
    display: flex;
    justify-content: space-between;

    .stat-item {
        text-align: center;
        flex: 1;

        .stat-value {
            font-size: 36rpx;
            font-weight: bold;
            color: #5b67ca;
            display: block;
            margin-bottom: 8rpx;
        }

        .stat-label {
            font-size: 24rpx;
            color: #666;
        }
    }
}
</style>
